package com.laoxu.java.practice.interview;

/**
 * 交换2个整形变量的几种方式
 *
 * @author laoxu
 * @create 2018-02-26
 **/
public class ExchangeTwoVariable {
    public static void main(String[] args) {
        exchangeByThirdVar();
        exchangeByPlusMinus();
        exchangeByXOR();
    }

    //1.借助临时变量
    private static void exchangeByThirdVar() {
        int a = 1, b = 2, tmp;
        tmp = a;
        a = b;
        b = tmp;

        System.out.println("a=" + a + " b=" + b);
    }

    //2.不借助第三变量，通过加减方式
    private static void exchangeByPlusMinus() {
        int a = 1, b = 2;
        a = a + b;
        b = a - b;
        a = a - b;

        System.out.println("a=" + a + " b=" + b);
    }

    //3.通过异或运算
    /*
        异或运算  ^ 规则：不同为1
        System.out.println( 1 ^ 2);

         * 1二进制 0001
         * 2二进制 0010
         * ----------
         *      0011 == 3
         *
         *
     */
    private static void exchangeByXOR() {
        int a = 1, b = 2;
        a = a ^ b;
        b = a ^ b; //1
        a = a ^ b; //2

        System.out.println("a=" + a + " b=" + b);
    }
}
